<script setup lang="jsx">
  import {watch,inject,ref,nextTick,reactive,computed} from 'vue'
import declareColumns from "@/utils/shipmentTools.js";
import addressLibDetail from "@/api/logistics/addressLibDetail.js";
import WithRadio from "@/views/document/shipment/components/withRadio.vue";
import WithSelect from "@/views/document/shipment/components/withSelect.vue";
import shipment from '@/api/document/shipment'
import { Message, Modal } from '@arco-design/web-vue'
import {auth, role} from '@/utils/common'
// import dicthelpApi from "@/api/dicthelpApi.js";
const columnsDist = inject('columnsDist')
// form 组件的 ref
const crudForm = ref()
const crudFormShow=ref(false)
// 表单数据
const form = ref({parcel:[],parcel_count:1,fba_count:'6',id:'',attrs:[],city:"",state:'',postcode:'',insurance:0,draft:0,})

const visible = ref(false)

const auditView = () => {
    return window.location.href.includes('shipmentAudit') == false
}
const getParcelData = (maFormObject, val,type) => {
    let formData = maFormObject.formModel.value
 
    let valLen=val
    //判断连续箱号点击
    if(type=='merge_number'){
      valLen=type
    }
    let count = val ? val : formData.parcel_count ? formData.parcel_count : 1
    let oldList = formData.parcel.splice(0, formData.parcel.length)
    let fba = fbaConfig.value.fba
    fba = fba.toUpperCase()
    oldList = oldList.splice(0,oldList.length-5)
    if(fbaConfig.value.merge_number && fbaConfig.value.merge_number.includes('1')){
        let item = oldList[0] ??{}

        item.ext_number =  count > 1 ? '1-' + count : '1'
        item.ext_number = fbaConfig.value.fba_check.includes('1') ? getExtNumber(fba,item,0) : splitStringAroundUAndZeros(item.ext_number)
        item.po_number = fbaConfig.value.po_number_check.includes('1') ? fbaConfig.value.po_number : item.po_number; 
        item.currency=fbaConfig.value.declaration_currency
        item.is_magnetic = fbaConfig.value.attrs.includes('4') ? '是':'否'
        item.is_elec = fbaConfig.value.attrs.includes('5') ? '是':'否'
        formData.parcel.push(item)
        return
    }else{
      if(valLen || oldList.length==0){
        for (let i = 0; i < count; i++) {
            let item = oldList[i] ??{}
            item.ext_number = i + 1
            formData.parcel.push(item)
          }
      }else{
        for (let i = 0; i < oldList.length; i++) {
            let item = oldList[i] ??{}
            formData.parcel.push(item)
         }
      }            
    }
    formData.parcel.map((item,index)=>{
        if(!item.ext_number){
            return
        }
        item.ext_number = fbaConfig.value.fba_check.includes('1') ? getExtNumber(fba,item,index) : splitStringAroundUAndZeros(item.ext_number);
        item.po_number = fbaConfig.value.po_number_check.includes('1') ? fbaConfig.value.po_number : item.po_number; 
        item.currency=fbaConfig.value.declaration_currency
        item.is_magnetic = fbaConfig.value.attrs.includes('4') ? '是':'否'
        item.is_elec = fbaConfig.value.attrs.includes('5') ? '是':'否'
    })
}

const splitStringAroundUAndZeros = (str)=>{
    str = String(str)
    const regex = /^(.*?)U(0+)(.*?)$/;
    const matches = str.match(regex);
    if(matches && matches.length > 3){
        return matches[3]
    }
    return str
}


const fbaConfig = ref({})

const service_id = ref([])
const user_id = ref(0)
const updateShow=ref(false)
const updateAddress = async (maFormObject) => {
    if (service_id.value && user_id.value) {
        let data = {user_id: user_id.value, service_id: service_id.value, type: 1}

        let res = await addressLibDetail.getAllList(data)
        let dicts = maFormObject.getColumnService().dicts
        dicts['address_lib_detail_id'] = res.data
        dicts['address_lib_detail_id']['tran'] = []
    }
}
const getExtNumber = (fba,item,index)=>{
    if(fbaConfig.value.merge_number && fbaConfig.value.merge_number.includes('1')){
        // 用 - 分割成数组
        let [extWithNumber,lastNumber] = item.ext_number.split('-')
        let firstNumber = extWithNumber.split('U').pop()
        return fba + 'U' + firstNumber.toString().padStart(fbaConfig.value.n,'0') + (lastNumber ? '-' + lastNumber :'')
    }
    return fba + 'U' + (index+1).toString().padStart(fbaConfig.value.n,'0')
}
const columns=ref([])
  const onShow = async (value) => {
    form.value = {parcel:[],parcel_count:1,fba_count:'6',id:'',attrs:[],city:"",state:'',postcode:'',insurance:0,draft:0,}
      columnsForm().then(res=>{
        console.log('res',res)
        columns.value=res
        updateShow.value=true
        visible.value = true
        nextTick(() => {
            crudFormShow.value=true
        })     
      })
    if(value){
      console.log('value',value)
      form.value=JSON.parse(JSON.stringify(value))
      if(form.value.address_lib_detail_id==null){
        form.value.address_lib_detail_id=''
      }
      if(form.value.to_depot_id){
        form.value.to_depot_id=form.value.to_depot_id.toString()
      }
      if(form.value.taxwith){
        form.value.taxwith=form.value.taxwith.toString()
      }
      if(form.value.deliverywith){
        form.value.deliverywith=form.value.deliverywith.toString()
      }
      if(form.value.exportwith){
        form.value.exportwith=form.value.exportwith.toString()
      }
      if(form.value.importwith){
        form.value.importwith=form.value.importwith.toString()
      }

      if(form.value.attrs==0){
        form.value.attrs=[]
      }
    }
    
  }
  const options = ref({
    showButtons:false,
  })
  const columnsForm= async (crudRef) => {
    return reactive([
  {
   
        formType: 'grid-tailwind',
        colNumber: 2,      
        cols: [
          {
            formList: [{
              dataIndex: 'user_id', title: '用户',formType: "select", customClass:['customer-input-item'],
              dict: {
                  data:columnsDist.value.dicthelpApi_customer.data,
                  props: {label:'nick', value: 'id'}, translation: true,
              },
              rules: [{ required: true, message: '请选择用户' }],
              virtualListProps:{},
              fixed: 'left',
                width: 140,
                addApi:()=>{                   
                },
              onChange: async (val, maFormObject) => {
                    if (!val) {
                        return;
                    }
                    user_id.value = val
                    updateAddress(maFormObject)
                }
            },{
              dataIndex: 'client_reference', title: '客户单号', 
            },{
              dataIndex: "service_id", title: "服务",formType: "select",
                fixed: 'left',
                width: 140,
              virtualListProps:{},
              rules: [{ required: true, message: '请选择服务' }],
                dict: {
                    data:columnsDist.value.dicthelpApi_service.data,
                    props: {label: 'name', value: 'id'}, translation: true,
                },
                onChange: async (val, maFormObject) => {
                    if (!val) {
                        return;
                    }
                    fbaConfig.value = {
                        n:'6',
                        fba: '',
                        fba_check: [],
                        attrs:maFormObject.formModel.value.attrs,
                        declaration_currency:'',
                        po_number: '',
                        po_number_check: [],
                    }
                    let dict = maFormObject.getColumnService().dicts
                    let parcel = maFormObject.getColumnService().get('parcel')             
                    let formData = maFormObject.formModel.value
                    let service;
                    dict['service_id'].map(i => {
                        if (val === i.value) {
                            service = i.data
                        }
                    })
                    // 处理交税报关方式等
                    let radioList = ['taxwith', 'deliverywith', 'exportwith', 'importwith'];
                    for (let i = 0; i < radioList.length; i++) {
                        let radio = radioList[i]
                        let service_radio = service[radio].toString()
                        let column = maFormObject.getColumnService().columns.filter(i => i.dataIndex === radio);
                        if (service['default_' + radio].toString() === '255') {
                            formData[radio] = ''
                            column[0].rules = [{required: true, message: '请选择' + column[0].title}];
                        } else if (service_radio.indexOf(formData[radio]) === -1) {
                            column[0].rules = []
                            formData[radio] = service['default_' + radio] ? service['default_' + radio].toString() : ''
                        }
                    }
                    // vat_number eori
                    // console.log('service',service)
                    maFormObject.getColumnService().columns.map(i => {
                        if(i.dataIndex == 'email' && service.bit_control.includes('17')){i
                            i.rules = {required: true, message: '请填写' + i.title}
                        }
                        if(i.dataIndex == 'phone' && service.bit_control.includes('18')){i
                            i.rules = {required: true, message: '请填写' + i.title}
                        }
                        if(i.dataIndex == 'vat_number' && service.bit_control.includes('3')){i
                            i.rules = {required: true, message: '请填写' + i.title}
                        }
                        if(i.dataIndex == 'eori' && service.bit_control.includes('2')){i
                            i.rules = {required: true, message: '请填写' + i.title}
                        }
                    })
                  
                    // 处理包裹信息
                    if(formData.parcel.length === 0){
                        getParcelData(maFormObject)
                    }
                    // 处理包裹申报信息
                    let list = await declareColumns.getDeclareColumns(service.id)
                    
                    list = declareColumns.formatDeclareColumns(list, 'create')
                    // console.log(list)
                    list.map(i=>{
                        if(i.title == '带电' || i.title == '带磁'){
                            i.type = 'dropdown'
                            i.source = ['否', '是']
                        }
                    })
                    parcel.setAttr('columns', list)
                    service_id.value = service.id
                    updateAddress(maFormObject)
                },                
                onControl: (val, maFormObject) => {
                  console.log(auth('document:waybill:number'))
                    if (form.value.id != '' && updateShow.value) {
                        user_id.value = crudForm.value.getFormData().user_id
                        service_id.value = val
                        updateShow.value=false

                        updateAddress(maFormObject)
                        return{                
                          user_id: {disabled: !!val,},
                          service_id: {disabled: !!val,},
                          country: {display: !!val,},
                          address_lib_detail_id: {display: !!val,},
                          declaration_currency: {display: !!val,},
                          taxwith: {display: !!val,},
                          deliverywith: {display: !!val,},
                          exportwith: {display: !!val,},
                          importwith: {display: !!val,},
                          po_number: {display: !!val,},
                          billing_time: {display: !!val,},  
                        }
                    }
                    if(form.value.status==7){
                      return {
                       draft: {display: auth('document:shipment:shipment_excel_batch_draft'),},
                      }
                    }
                   if(form.value.id==''){
                    return {
                        parcel_count: {display: !!val,},
                        merge_number: {display: !!val,},
                        fba: {display: !!val,},
                        po_no: {display: !!val,},
                        parcel: {display: !!val,},
                        taxwith: {display: !!val,},
                        deliverywith: {display: !!val,},
                        exportwith: {display: !!val,},
                        importwith: {display: !!val,},
                        declaration_currency: {display: !!val,},
                        country: {display: !!val,},
                        address_lib_detail_id: {display: !!val,},
                        draft: {display: auth('document:shipment:shipment_excel_batch_draft'),},
                        
                    };
                   }
                  
                    
                }
            },
            {
                title: "预约送仓",
                dataIndex: "to_depot_id",
                formType: "select",
                dict: {               
                    data:columnsDist.value.dicthelpApi_depot.data,
                    // 指定组件接收的props
                    props: {label: 'name', value: 'id'},
                    translation: true,
                },
                rules: {
                    required: true,
                    message: "请选择预约仓库"
                },
            },
            {                            
              dataIndex: 'address_lib_detail_id',formType: 'select', title: '地址库',virtualListProps:{}, // todo 展示地址库编码
                dict: {
                    data:columnsDist.value.dicthelpApi_addressLibDetail.data,
                    props: {label: (i) => i.code + '-' + i.postcode, value: 'id'},
                    translation: true,
                },
                onChange: (val, maFormObject) => {
                    let dicts = maFormObject.getColumnService().dicts
                    if (typeof dicts['address_lib_detail_id'] === 'undefined') {
                        return;
                    }
                    let formData = maFormObject.formModel.value
                    if (val === 0) {
                        return;
                    }
                    if (val === '') {
                        formData.address_lib_detail_id = 0
                        formData.name = ''
                        formData.address1 = ''
                        formData.address2 = ''
                        formData.address3 = ''
                        formData.city = ''
                        formData.state = ''
                        formData.country = ''
                        formData.postcode = ''
                        formData.phone = ''
                        formData.email = ''
                        formData.company = ''
                        return;
                    }
                    for (const valElement of dicts['address_lib_detail_id']) {
    
                        if (valElement.value === val) {
                            let address = valElement.data
                            formData.name = address.name
                            formData.address1 = address.address_1
                            formData.address2 = address.address_2
                            formData.address3 = address.address_3
                            formData.city = address.city
                            formData.state = address.state
                            formData.country = address.country
                            formData.postcode = address.postcode
                            formData.phone = address.mobile
                            formData.email = address.email
                            formData.company = address.company
                        }
                    }
                }
            },
            {
                title: '收件人',dataIndex: 'name',
                rules: [{ required: true, message: '请输入收件人' }],            
            },
            {title: '公司', dataIndex: 'company',},
            {
                title: '地址一',dataIndex: 'address1',
                rules: [{ required: true, message: '请输入地址一' }],            
            },
            {
                title: '地址二',dataIndex: 'address2',            
            },
            {
                title: '地址三',dataIndex: 'address3',           
            },
            {
                formType: 'group',
                bordered: false,
                customClass: ['form-inline-card'],
                size: 'small',
                title: '城市/州/邮编',
                formList: [
                  {dataIndex: 'city', title: '城市'},
                  {dataIndex: 'state', title: '州/省'},
                  {dataIndex: 'postcode', title: '邮编'},
                ]
              },
              {
                title: '国家',dataIndex: 'country',
                formType: "select",
                dict: {
                    data:columnsDist.value.dictObj.data.countrys,
                    props: {label: (i) => i.title + '-' + i.key, value: "key"},                 
                },
                rules: [{ required: true, message: '请选择国家' }],            
              },
              {
                  title: '电话',dataIndex: 'phone',            
              },
              {
                  title: '邮箱',dataIndex: 'email',           
              },
          ]
          },
          {
            formList: [{
              dataIndex: 'self_reference', title: '关联单号',
            },
            {
              dataIndex: 'reference_1', title: '参考号一',
            },
            {
              dataIndex: 'reference_2', title: '参考号二',
            },
            {
                title: '物品属性',dataIndex: 'attrs',
                formType: "checkbox",
                dict: {
                    data:columnsDist.value.dictObj.data.ShipmentAttrs,
                    props: {label: 'title', value: 'key'},
                    translation: true,
                },
                onChange: (val, maFormObject) => {
                    fbaConfig.value.attrs = val              
                    if (form.value.service_id && form.value.id=='') {
                      getParcelData(maFormObject)
                    }
                    
                },          
            },
            {
              title: '申报币种',dataIndex: 'declaration_currency',
              formType: "select",
              dict: {
                  data:columnsDist.value.dictObj.data.currencyType,
                  props: {label: 'title', value: 'key'},
                  translation: true,
              },  
              rules: [{ required: true, message: '请选择申报币种' }],  
              onChange: (val, maFormObject) => {
                    fbaConfig.value.declaration_currency = val                               
                    getParcelData(maFormObject)                                      
                },            
            },
            {          
              title: 'PO NUMBER',dataIndex: 'po_number',display:false,      
            },
            {          
              title: '主品名',dataIndex: 'main_name',      
            },
            {title: "交税方式", dataIndex: "taxwith", formType: 'radio', type: 'button', 
            dict: {
              data:columnsDist.value.dictObj.data.taxwith,
              props: {label: 'title', value: 'key'}}, 
          },
            {title: "交货条款", dataIndex: "deliverywith", formType: 'radio', type: 'button',
              dict: {
                data:columnsDist.value.dictObj.data.deliverywith,
                props: {label: 'title', value: 'key'}},
            },
            {title: "报关方式", dataIndex: "exportwith", formType: 'radio', type: 'button', 
              dict: {
                data:columnsDist.value.dictObj.data.exportwith,             
                props: {label: 'title', value: 'key'}},
            },
            {title: "清关方式", dataIndex: "importwith",formType: 'radio', type: 'button', 
              dict: {
                data:columnsDist.value.dictObj.data.importwith,
                props: {label: 'title', value: 'key'}},
            },
            {title: "VAT号", dataIndex: "vat_number", },
            {title: "IOSS号", dataIndex: "ioss", },
            {title: "EORI", dataIndex: "eori", },
            {title: "内部备注", dataIndex: "internal_remark", formType: "textarea", },
            {title: "备注", dataIndex: "remark", formType: "textarea", },
            {title: "购买保险", dataIndex: "insurance", 
              formType: 'radio', type: 'button',
              dict:{
                data:[
                  {value:1,label:'是'},
                  {value:0,label:'否'},
                ],
              }
            },
            {title: "是否是草稿", dataIndex: "draft", 
              formType: 'radio', type: 'button',
              display:false,
              dict:{
                data:[
                  {value:1,label:'是'},
                  {value:0,label:'否'},
                ],
              }
            },
            {title: "计费时间", dataIndex: "billing_time", formType: "date", display:false,},
          ]
          },         
        ]
      },
      {
        formType: 'grid-tailwind',
        colNumber: 6,
        cols: [
          {
            colNumber: 3,
            formList:[
              {dataIndex: 'parcel_count', 
              display:false,
               title: "件数",formType: "input-number",min:1,
              rules: [{ required: true, message: '请输入包裹数量' }],  
              allowClear:false, 
              onChange: (val, maFormObject) => {
                    if (form.value.id != '') {
                        return false
                    }
                    let dict = maFormObject.getColumnService().dicts
                    if (typeof dict['service_id'] === 'undefined') {
                        return;
                    }
                    let formData = crudForm.value.getFormData()
                    if (val > 0 && formData.service_id) {
                        getParcelData(maFormObject, val)
                    }
                },       
              },
              {title:'FBA号',dataIndex:'fba_number',
              display:false,
                onInput: (val, maFormObject) => {
                  if (form.value.id != '') {
                        return false
                    }
                    fbaConfig.value.fba = val
                    getParcelData(maFormObject)
                }
            },
            ]
          },
          {
            colNumber: 1,
            formList:[
              {
                title: '',
                formType: 'checkbox',
                 display:false,
                dataIndex: 'fba',
                dict:{
                    data:[{label: 'FBA',value:1}],
                    translation:true
                },
                onChange: (val, maFormObject) => {
                    fbaConfig.value.fba_check = val
                    getParcelData(maFormObject)
                },
                onControl: (val, maFormObject) => {
                    if (form.value.id != '') {
                        return false
                    }
                   
                      return {
                        fba_count: {display: val.includes('1'),},
                        fba_number: {display: val.includes('1'),},
                    }
                    
                   
                }
              },
              {dataIndex: 'fba_count',
                title: '箱号位数',
                formType: 'radio',
                display:false,
                type: 'button',
                dict:{
                    data:[{label: '3',value:'3'},{label: '6',value:'6'},],
                },
                onChange: (val, maFormObject) => {
                    fbaConfig.value.n = val
                    getParcelData(maFormObject)
                }

              },
            ]
          },
          {
            colNumber: 2,
            formList:[
              {dataIndex: 'po_no', formType: 'checkbox',
              display:false,
                dict:{
                  data:[{label: 'PO_Number',value:1}],
                  translation:true
              },
              onChange: (val, maFormObject) => {
                  fbaConfig.value.po_number_check = val
                  getParcelData(maFormObject)
              },
              onControl: (val, maFormObject) => {
                if (form.value.id != '') {
                        return false
                }
                  return {
                      parcel_po_number: {display: val.includes('1'),},
                  }                  
              }
              },
              {dataIndex: 'parcel_po_number',
              display:false,
                title:'PO_Number',
                  onInput: (val, maFormObject) => {
                    if (form.value.id != '') {
                        return false
                    }
                    fbaConfig.value.po_number = val
                    getParcelData(maFormObject)
                }
              },
            ]
          },
          {
            colNumber: 1,
            formList:[{dataIndex: 'merge_number',formType: 'checkbox',
            display:false,
            dict:{data:[{label: '连续箱号',value:1}]},
                onChange: (val, maFormObject) => {
                  if (form.value.id != '') {
                        return false
                    }
                    fbaConfig.value.merge_number = val
                    if (val && crudForm.value.getFormData().service_id) {
                        getParcelData(maFormObject,'','merge_number')
                    }
                },
            }]
          },
        ]
      },
      {title: "包裹", dataIndex: "parcel", formType: 'datagrid', 
            display:false,
            columns: [],
            dict: {
              data:columnsDist.value.dictObj.data.BitControl,
              props: {label: 'title', value: 'key'}}, 
          },
    ])
  }
  const formLoading=ref(false)
const emits = defineEmits(['addClick','emitClick'])
  //新增 //编辑
  const handleBeforeOk =async () => {
    if (await crudForm.value.validateForm()) {
      return false
    }
    console.log('form',form)
    formLoading.value=true
    let formParse = JSON.parse(JSON.stringify(form.value)); // 深拷贝数据
    let parcelList = formParse.parcel.filter(item => item.ext_number!== null);
    formParse.parcel=parcelList
          if(form.value.id==''){
            shipment.save(formParse).then(res => {
              if(res.success){
                Message.success(res.message || `新增成功！`);
              emits('addClick');
              close()
              }else{
                Message.warning(res.message)

              }
              
            }).finally(()=>{
              formLoading.value=false
            })
          }else{
            shipment.update(formParse).then(res => {
              if(res.success){
                Message.success(res.message || `编辑成功！`)    
              emits('emitClick');
              close()
              }else{
                Message.warning(res.message)

              }
            }).finally(()=>{
              formLoading.value=false
            })
          }
      
    };
    const close = () => {
      visible.value = false
      crudForm.value.resetForm();
      columns.value = []
      crudFormShow.value=false
      // form.value = {parcel:[],parcel_count:1,fba_count:'6',id:''}
    }
const onBeforeCancel=()=>{
  Modal.confirm({
        title: '确认关闭?',
        onOk: () => {
          close()
        },
      });
}
defineExpose({ onShow })
</script>

<template>
  <a-drawer v-model:visible="visible" width="80%" :onBeforeCancel="onBeforeCancel">
    <template #title><div >{{  form.id == "" ? '新增' : '编辑'}}</div></template>
    <ma-form v-if="columns.length>0"  v-model="form" ref="crudForm" :options="options" :columns="columns">
           <!--  表单插槽    -->
        <template #form-taxwith="component" v-if="crudFormShow">
          <with-radio :component="component" :crudForm="crudForm" type="taxwith"/>
        </template>
        <template #form-deliverywith="component" v-if="crudFormShow">
          <with-radio :component="component" :crudForm="crudForm" type="deliverywith"/>
        </template>
        <template #form-exportwith="component" v-if="crudFormShow">
          <with-radio :component="component" :crudForm="crudForm" type="exportwith"/>
        </template>
        <template #form-importwith="component" v-if="crudFormShow">
          <with-radio :component="component" :crudForm="crudForm" type="importwith"/>
        </template>
        <template #form-declaration_currency="component" v-if="crudFormShow">
          <with-select :component="component" :crudForm="crudForm" serviceIndex="currency_type"/>
        </template>
        <template #form-country="component" v-if="crudFormShow">
          <with-select :component="component" :crudForm="crudForm" serviceIndex="country"/>
        </template> 
      </ma-form>
      <template #footer>        
          <a-button @click="onBeforeCancel">关闭</a-button>
          <a-button type="primary" :disabled="formLoading" @click="handleBeforeOk(crudForm)">
            保存
          </a-button>
        </template>
  </a-drawer>
</template>